# -*- coding: utf-8 -*-
#  @author  Bink
#  @date  2020/12/22 9:14 上午
#  @Email : 2641032316@qq.com

import pandas as pd
import fileinput
import numpy as np
import matplotlib.pyplot as plt
import sys
import os

sys.path.append(os.getcwd() + '/scr')
from subFunction import *

train_path = './data/dsjtzs_txfz_training.txt'
test_path = './data/dsjtzs_txfz_test1.txt'

# mouseTrack_features_labels = ['numRecode', 'xmean', 'ymean', 'xEnt', 'yEnt', 'MaxTimeInterval', 'MinTimeInterval',
#                               'tailXdiff', 'tailYdiff', 'tailTdiff', 'tailDis_xy', 'Vmean', 'Vmax', 'Vmin', 'Vvar',
#                               'Vstd', 'Accmean', 'Accmax', 'Accmin', 'Accvar', 'Accstd', 'LastT20var',
#                               'LastT20std', 'Vcov', 'VCorrelationCoefficient', 'XdiffVar', 'YdiffVar']
mouseTrack_features_labels = ['numRecode', 'xmean', 'ymean', 'xEnt', 'yEnt', 'MaxTimeInterval', 'MinTimeInterval',
                              'tailXdiff', 'tailYdiff', 'tailTdiff', 'tailDis_xy', 'Vmean', 'Vmax', 'Vmin', 'Vvar',
                              'Vstd', 'Accmean', 'Accmax', 'Accmin', 'Accvar', 'Accstd', 'LastT20var',
                              'LastT20std', 'XdiffVar', 'YdiffVar']
featureLabels = ['id']
featureLabels.extend(mouseTrack_features_labels)
featureLabels.extend(['YTarget', 'XTarget', 'label'])


# 获取ｘ，ｙ的平均值 .２个特征
def get_XYmean(df_MouseTrack):
    x = df_MouseTrack["x"]
    y = df_MouseTrack["y"]
    xmean = np.mean(x)
    ymean = np.mean(y)
    xymean = [xmean, ymean]
    return xymean


# 获取x,y的熵　２个特征
def get_XYentropy(df_MouseTrack):
    x = df_MouseTrack["x"]
    y = df_MouseTrack["y"]
    xEnt = calcShannonEnt(x)
    yEnt = calcShannonEnt(y)
    xyEnt = [xEnt, yEnt]
    return xyEnt


# 获取间隔时间的最大值和最小值　２个特征
def get_MaxMinT(df_MouseTrack):
    print()
    if len(df_MouseTrack) < 2:
        t = df_MouseTrack['t']
        return t, t
    else:
        maxT = df_MouseTrack['t'].max()
        minT = df_MouseTrack['t'].min()
        return maxT, minT


# 获取最后一个时间段x,y,t的差分值，以及两个点之间的欧氏距离　４个特征
def get_tailFeature(df_MouseTrack):
    if len(df_MouseTrack) < 2:
        xdiff = 0
        ydiff = 0
        tdiff = 0
        dis = 0
        diff_and_Dis = [xdiff, ydiff, tdiff, dis]
    else:
        xdiff = calDiffenceResult(df_MouseTrack['x'])
        ydiff = calDiffenceResult(df_MouseTrack['y'])
        tdiff = calDiffenceResult(df_MouseTrack['t'])
        dis = np.sqrt(xdiff.iloc[-1].values ** 2 + ydiff.iloc[-1].values ** 2)
        diff_and_Dis = [xdiff.iloc[-1].values[0], ydiff.iloc[-1].values[0], tdiff.iloc[-1].values[0], dis[0]]
    return diff_and_Dis


# 速度的平均值，最大值，最小值，方差，标准差　５个特征
def get_xv_var(df_MouseTrack):
    if len(df_MouseTrack) < 2:
        speedMean = 0
        speedMax = 0
        speedMin = 0
        speedVar = 0
        speedStd = 0
    else:
        speed = calSpeed(df_MouseTrack)
        speedMean = speed.mean()[0]
        speedMax = speed.max()[0]
        speedMin = speed.min()[0]
        speedVar = speed.var()[0]
        speedStd = speed.std()[0]
    speedFeat = [speedMean, speedMax, speedMin, speedVar, speedStd]
    return speedFeat


# 加速度的平均值，最大值，最小值，方差，标准差　5个特征
def get_Acc_feat(df_MouseTrack):
    if len(df_MouseTrack) < 3:
        meanAcc = 0
        maxAcc = 0
        minAcc = 0
        varAcc = 0
        stdAcc = 0
    else:
        t = df_MouseTrack['t']
        t1 = np.array(t[0:-1])
        t2 = np.array(t[1:])
        v_t = (t1 + t2) / 2
        v_tdiff = calDiffenceResult(v_t)
        speed = calSpeed(df_MouseTrack)
        SPdiff = calDiffenceResult(speed)
        Accelearation = SPdiff / v_tdiff
        if len(Accelearation) == 0:
            end = 1
        meanAcc = Accelearation.mean()[0]
        maxAcc = Accelearation.max()[0]
        minAcc = Accelearation.min()[0]
        varAcc = Accelearation.var()[0]
        stdAcc = Accelearation.std()[0]
        # reciprocalAcc = 1/Accelearation
    AccFeat = [meanAcc, maxAcc, minAcc, varAcc, stdAcc]
    return AccFeat


# 采样最后２０段时间的方差和标准差　２个特征
def get_t_last20_var(df_MouseTrack):
    tdiff = calDiffenceResult(df_MouseTrack['t'])
    if len(tdiff) >= 20:
        useTdiff = tdiff[-20:]
    else:
        useTdiff = tdiff
    Tvar = useTdiff.var()[0]
    Tstd = useTdiff.std()[0]
    T20feat = [Tvar, Tstd]
    return T20feat


# 记录速度的协方差，及相关系数　２个特征
def get_vx_cov_reverse(df_MouseTrack):
    if len(df_MouseTrack) < 4:
        CovXY = 0
        CorrelationCoefficient = 0
    else:
        v = calSpeed(df_MouseTrack)
        v1 = v[0:-1]
        v2 = v[1:]
        vCov = np.cov(v1, v2)  # 协方差矩阵
        CovXY = vCov[0, 1]  # v1和v2的协方差
        CorrelationCoefficient = CovXY / (np.sqrt(vCov[0, 0]) * np.sqrt(vCov[1, 1]))  # 求解相关系数
    vFeat = [CovXY, CorrelationCoefficient]
    return vFeat


# 水平和垂直位移的方差　２个特征
def get_XYvar(df_MouseTrack):
    xdiff = calDiffenceResult(df_MouseTrack['x'])
    ydiff = calDiffenceResult(df_MouseTrack['y'])
    XDiffvar = xdiff.var()[0]
    YDiffvar = ydiff.var()[0]
    disVar = [XDiffvar, YDiffvar]
    return disVar


# 时间噪声
def get_t_noisiness(df_MouseTrack):
    end = 1


# 获取鼠标轨迹特征
def getFeatures(df_MouseTrack):
    m = len(df_MouseTrack)
    features = []
    features.append(m)

    XYmean = get_XYmean(df_MouseTrack)
    features.extend(XYmean)

    XYEnt = get_XYentropy(df_MouseTrack)
    features.extend(XYEnt)

    MaxMinT = get_MaxMinT(df_MouseTrack)
    features.extend(MaxMinT)

    tailfeat = get_tailFeature(df_MouseTrack)
    features.extend(tailfeat)

    vfeat = get_xv_var(df_MouseTrack)
    features.extend(vfeat)

    accfeat = get_Acc_feat(df_MouseTrack)
    features.extend(accfeat)

    last20tVar = get_t_last20_var(df_MouseTrack)
    features.extend(last20tVar)

    # diffVfeat = get_vx_cov_reverse(df_MouseTrack)
    # features.extend(diffVfeat)

    xyVar = get_XYvar(df_MouseTrack)
    features.extend(xyVar)

    return features


def make_train_data():
    traindata = pd.DataFrame(np.random.randn(10, len(featureLabels)), columns=featureLabels)
    for i, line in enumerate(fileinput.input('/Users/bink/pra/scala/ml/MouseDetection/in/dsjtzs_txfz_training.txt')):
        # print(line)
        if int(i) % 100 == 0:
            print(i)
        features = []
        line = line.split()
        a1 = int(line[0])  # 获取编号id
        features.append(a1)

        a2 = line[1].split(";")
        temp = [x.split(',') for x in a2]
        temp.pop()
        a2 = np.mat(temp, dtype=float)
        a2 = pd.DataFrame(a2, columns=list('xyt'))
        a2 = a2.groupby('t', as_index=False).first()
        # print(type(a2))
        # print(a2)
        # print(a2.shape)
        # print('*'*99)
        if len(a2) < 2:
            continue
        a2_feature = getFeatures(a2)
        features.extend(a2_feature)

        a3 = line[2].split(',')  # 目标点的坐标
        a3_x = float(a3[0])
        a3_y = float(a3[1])

        features.append(a3_x)  # ｘ坐标
        features.append(a3_y)  # ｙ坐标

        label = int(line[3])  # 标签
        features.append(label)

        feature = pd.DataFrame(np.array(features), index=traindata.columns)
        feature.fillna(0).to_csv('output/train.csv', mode='a+', index=None, header=None, sep=';', line_terminator=';', float_format='%.6f')
        with open('output/train.csv', mode='a+') as f:
            f.write('\n')
        # print(feature.index)
        # print(feature)
        # traindata.append(feature)
        # print(feature)
        # print(feature.index)
        # print(traindata.index)
    return traindata


def make_test_data():
    testFeatlabels = featureLabels
    testFeatlabels.pop()  # 测试样本数据集比训练样本集少一个标签“label”
    testdata = pd.DataFrame(np.random.randn(1, len(testFeatlabels)), columns=testFeatlabels)
    for i, line in enumerate(fileinput.input('/Users/bink/pra/scala/ml/MouseDetection/in/dsjtzs_txfz_test.txt')):
        features = []
        line = line.split()
        a1 = int(line[0])  # 获取编号id
        features.append(a1)

        a2 = line[1].split(";")
        temp = [x.split(',') for x in a2]
        temp.pop()
        a2 = np.mat(temp, dtype=float)
        a2 = pd.DataFrame(a2, columns=list('xyt'))
        if len(a2) < 3:
            pause = 1
        a2 = a2.groupby('t', as_index=False).first()
        a2_feature = getFeatures(a2)
        features.extend(a2_feature)

        a3 = line[2].split(',')  # 目标点的坐标
        a3_x = float(a3[0])
        a3_y = float(a3[1])
        features.append(a3_x)  # ｘ坐标
        features.append(a3_y)  # ｙ坐标

        feature = pd.DataFrame(np.array(features), index=testdata.columns)
        feature.fillna(0).to_csv('output/test.csv', mode='a+', index=None, header=None, sep=';', line_terminator=';',
                                 float_format='%.6f')
        with open('output/test.csv', mode='a+') as f:
            f.write('\n')

        # testdata.iloc[i] = pd.Series(np.array(features), index=testdata.columns)

    return testdata


if __name__ == '__main__':
    # traindata = make_train_data()
    # print(traindata)
    testData = make_test_data()